package com.gao.f_reactor.d.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author gao
 * @time 2020/08/23 19:03:54
 */
public class NioClient {
    private Selector selector;
    private SocketChannel channel;
    private int port;
    private Scanner sc = new Scanner(System.in);

    public NioClient(int port) {
        try {
            this.port = port;
            selector = Selector.open();
            channel = SocketChannel.open();
            channel.configureBlocking(false);
            boolean bb = channel.connect(new InetSocketAddress(port));
            if (!bb) {
                channel.register(selector, SelectionKey.OP_CONNECT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                int n = selector.select();
                if (n > 0) {
                    Set<SelectionKey> selectedKeys = selector.selectedKeys();
                    Iterator<SelectionKey> it = selectedKeys.iterator();
                    while (it.hasNext()) {
                        SelectionKey key = it.next();
                        it.remove();
                        if (key.isValid() && key.isConnectable()) {
                            connect(key);
                        }
                        if (key.isValid() && key.isWritable()) {
                            write(key);
                        }
                        if (key.isValid() && key.isReadable()) {
                            read(key);
                        }
                    }
                }
            }
        } catch (IOException e) {

        }
    }

    private void read(SelectionKey key) {
        try {
            SocketChannel channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(100);
            int n = channel.read(buffer);
            buffer.flip();
            byte[] readBytes = new byte[n];
            buffer.get(readBytes);
            String msg = new String(readBytes);
            System.out.println(msg);

            key.interestOps(SelectionKey.OP_WRITE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void write(SelectionKey key) {
        try {
            SocketChannel channel = (SocketChannel) key.channel();
            System.out.println("请输入要发送给服务器的消息：（eg. what's the time）");
            String msg = sc.nextLine();
            if ("".equals(msg)) {
                return;
            }
            channel.write(ByteBuffer.wrap(msg.getBytes()));
            if ("bye".equalsIgnoreCase(msg)) {
                key.cancel();
                channel.close();
                System.out.println("从服务器断开连接");
            } else {
                key.interestOps(SelectionKey.OP_READ);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void connect(SelectionKey key) {
        try {
            SocketChannel channel = (SocketChannel) key.channel();
            channel.finishConnect();
            System.out.println("客户端连接到服务器");
            channel.register(selector, SelectionKey.OP_WRITE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        NioClient client = new NioClient(8888);
        client.start();
    }
}
